package cn.dgut.lemon.springbootexp03.controller;

import cn.dgut.lemon.springbootexp03.model.RegionStats;
import cn.dgut.lemon.springbootexp03.service.CoronaVirusDataService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.time.LocalDate;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Lemon
 * @data 2020-11-18 21:35
 */

@Controller
@RequiredArgsConstructor
public class HomeController {

    private final CoronaVirusDataService coronaVirusDataService;

    @GetMapping("/")

    public String home(Model model, String country) {
        List<RegionStats> allStats;
        if (country == null ) {
            allStats = coronaVirusDataService.getAllRegionStats();
        } else {
            allStats = Collections.unmodifiableList(coronaVirusDataService.getAllRegionStats()
                    .parallelStream()
                    .filter(locationStats -> locationStats.getCountry().equals(country))
                    .collect(Collectors.toList()));
        }

        // 设置查询条件
        model.addAttribute("country", country);

        // 使用parallelStream统计数据
        int totalReportedCases = allStats.parallelStream().mapToInt(RegionStats::getLatestTotalCases).sum();
        int totalNewCases = allStats.parallelStream().mapToInt(RegionStats::getDiffFromPrevDay).sum();

        model.addAttribute("regionStats", allStats);
        model.addAttribute("totalReportedCases", totalReportedCases);
        model.addAttribute("totalNewCases", totalNewCases);

        // 获取当前日期
        model.addAttribute("localDate", LocalDate.now());

        return "index";
    }
}
